﻿using AgoraChat;
using chatSDKApp;
using DevComponents.DotNetBar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace chatSDKApp.Forms.ChatRoom
{
    public partial class ChatManageFrom : Office2007Form
    {
        public static Dictionary<string, Dictionary<string, UserInfo>> _dicGroupMembers = new Dictionary<string, Dictionary<string, UserInfo>>();

        ChatSdkClass chatSdkClass = new ChatSdkClass();

        public ChatManageFrom(Dictionary<string, Dictionary<string, UserInfo>> dicGroupMembers)
        {
            InitializeComponent();
            this.EnableGlass = false;//使用donetBar样式
            _dicGroupMembers = dicGroupMembers;
        }

        /// <summary>
        /// 控件绑定数据源
        /// </summary>
        public void bindingData()
        {
            //绑定群
            bindingGroup();
        }

        /// <summary>
        /// 绑定群数据
        /// </summary>
        private void bindingGroup()
        {
            try
            {
                cmbGroup.DataSource = null;
                cmbGroup2.DataSource = null;
                //构造数据源（或从数据库中查询）  
                DataTable ADt = new DataTable();
                DataColumn ADC1 = new DataColumn("GROUP_ID", typeof(string));
                DataColumn ADC2 = new DataColumn("GROUP_Name", typeof(string));
                ADt.Columns.Add(ADC1);
                ADt.Columns.Add(ADC2);

                foreach (var item in ChatSdkClass.groupList)
                {
                    DataRow ADR = ADt.NewRow();
                    ADR[0] = item.GroupId;
                    ADR[1] = item.Name;
                    ADt.Rows.Add(ADR);
                }
                //进行绑定  
                cmbGroup.DisplayMember = "GROUP_Name";//控件显示的列名  
                cmbGroup.ValueMember = "GROUP_ID";//控件值的列名  
                cmbGroup.DataSource = ADt;

                cmbGroup2.DisplayMember = "GROUP_Name";//控件显示的列名  
                cmbGroup2.ValueMember = "GROUP_ID";//控件值的列名  
                cmbGroup2.DataSource = ADt;
            }
            catch (Exception ex)
            {

                LogHelper.Log("bindingGroup", ex.ToString());
            }
        
        }

        /// <summary>
        /// 绑定数据源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChatManageFrom_Load(object sender, EventArgs e)
        {
            //chatSdkClass = new ChatSdkClass();
            //绑定数据
            bindingData();
        }

        /// <summary>
        /// 退群
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btLeaveGroup_Click(object sender, EventArgs e)
        {
            var groupId = cmbGroup.SelectedValue.ToString();

            //根据群聊id获取群信息
            Group group = SDKClient.Instance.GroupManager.GetGroupWithId(groupId);
            var CurrentUsername = SDKClient.Instance.CurrentUsername;
            if (group.Owner != CurrentUsername)
            {
                if (MessageBox.Show("您确认退出群聊吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //退群
                    chatSdkClass.LeaveGroup(groupId);
                }
               
            }
            else
            {
                if (MessageBox.Show("您确认解散群聊吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //解散群
                    chatSdkClass.DestroyGroup(groupId);
                }
             
            }

          
        }

        /// <summary>
        /// 加群
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btJoinGroup_Click(object sender, EventArgs e)
        {
            var groupId = txtJoinGroup.Text;
            if (string.IsNullOrWhiteSpace(groupId))
            {
                MessageBoxEx.Show("请输入群号", "错误提示");
            }
            else
            {
                if (groupId.Length != 15)
                {
                    MessageBoxEx.Show("请输入正确群号", "错误提示");
                }
                else
                {
                    //加入群
                    chatSdkClass.JoinGroup(groupId);
                }
            }
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCreateUser_Click(object sender, EventArgs e)
        {
            var UserId = txtNewUserId.Text.Trim();
            var pwd =txtPwd.Text.Trim();
            var confirmPwd = txtConfirmPwd.Text.Trim();

            if (string.IsNullOrWhiteSpace(UserId))
            {
                MessageBoxEx.Show("请输入添加的用户Id!", "错误提示");
                return;
            }

            if (string.IsNullOrWhiteSpace(pwd))
            {
                MessageBoxEx.Show("请输入用户的密码!", "错误提示");
                return;
            }

            if (string.IsNullOrWhiteSpace(confirmPwd))
            {
                MessageBoxEx.Show("请输入确认密码!", "错误提示");
                return;
            }

            if ( pwd != confirmPwd)
            {
                MessageBoxEx.Show("密码输入不一致，请确认!", "错误提示");
                return;
            }

            //创建新用户
            chatSdkClass.CreateAccount(UserId, pwd);
        }

        /// <summary>
        /// 添加好友
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddFriend_Click(object sender, EventArgs e)
        {
            var UserId = txtUserId1.Text.Trim();
            if (string.IsNullOrWhiteSpace(UserId))
            {
                MessageBoxEx.Show("请输入添加的用户Id", "错误提示");
            }
            else
            {
                //加好友
                chatSdkClass.AddContact(UserId);

            }
        }

        /// <summary>
        /// 删除好友
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btDelFriend_Click(object sender, EventArgs e)
        {
            var UserId = txtUserId1.Text.Trim();
            if (string.IsNullOrWhiteSpace(UserId))
            {
                MessageBoxEx.Show("请输入添加的用户Id", "错误提示");
            }
            else
            {
                //删除好友
                chatSdkClass.DeleteContact(UserId);

            }
        }

        /// <summary>
        /// 查找群信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btGroupInfo_Click(object sender, EventArgs e)
        {
            var groupId = cmbGroup2.SelectedValue.ToString();
            //根据群组 ID 从服务器获取群组详情。
            SDKClient.Instance.GroupManager.GetGroupSpecificationFromServer(groupId, new ValueCallBack<Group>(
                onSuccess: (group) => {
                    richTxtGroupInfo.Text += "群号码：" + group.GroupId + "\r\n";
                    richTxtGroupInfo.Text += "群主：" + group.Owner + "\r\n";
                    richTxtGroupInfo.Text += "群成员数：" + group.MemberCount + 1 + "\r\n";
                    richTxtGroupInfo.Text += "群成员：" + "\r\n";

                    richTxtGroupInfo.Text += "工号：" + group.Owner + " 姓名：" + (_dicGroupMembers[groupId][group.Owner]).NickName + "\r\n";//群主不包含在内
                    foreach (var item in group.MemberList)
                    {
                        richTxtGroupInfo.Text += "工号：" + item + " 姓名："+ (_dicGroupMembers[groupId][item]).NickName +  "\r\n";
                    }
                    richTxtGroupInfo.Text += "=====================" + "\r\n";
                },
                onError: (code, desc) =>
                {
                    MessageBoxEx.Show($"获取群信息失败,code:{code}, desc:{code}", "失败");
                }
            ));

        }

        /// <summary>
        /// 查找好友信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btFriendInfo_Click(object sender, EventArgs e)
        {
            var UserId = txtUserId2.Text;

            //获取一个或多个用户的所有属性，一次调用用户 ID 数量不超过 100。
            List<string> idList = new List<string>();
            idList.Add(UserId);
            SDKClient.Instance.UserInfoManager.FetchUserInfoByUserId(idList, new ValueCallBack<Dictionary<string, UserInfo>>(
            onSuccess: (result) => {
                foreach (var item in result)
                {
                    richTxtFriendInfo.Text += "工号：" + item.Key.ToString() + "\r\n";
                    richTxtFriendInfo.Text += "用户名：" + item.Value.NickName + "\r\n";
                    richTxtFriendInfo.Text += "电话：" + item.Value.PhoneNumber + "\r\n";
                    richTxtFriendInfo.Text += "邮箱：" + item.Value.Email + "\r\n";
                    richTxtFriendInfo.Text += "=====================" + "\r\n";
                }
             
            },
            onError: (code, desc) => {
                MessageBoxEx.Show($"获取用户信息失败,code:{code}, desc:{code}", "失败");
            }
));

        }

        /// <summary>
        /// 更新用户信息，只能更新当前用户自己的信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btUpdateInfo_Click(object sender, EventArgs e)
        {
            // 设置所有用户属性。
            UserInfo userInfo = new UserInfo();
            userInfo.UserId = txtUpdateUserId.Text.Trim();
            userInfo.NickName = txtNickName.Text.Trim();
            //userInfo.PhoneNumber = txtTelPhone.Text.Trim();
            //userInfo.Email = txtEmail.Text.Trim();

            //其他信息
            // userInfo.avatarUrl = "http://www.easemob.com";
            // userInfo.birth = "1998.10.10";
            // userInfo.signature = "签名";
            // userInfo.gender = 1;

            SDKClient.Instance.UserInfoManager.UpdateOwnInfo(userInfo, new CallBack(
                onSuccess: () => {
                    MessageBoxEx.Show("更新信息成功!", "成功");
                },
                onError: (code, desc) => {

                    MessageBoxEx.Show($"更新信息失败,code:{code}, desc:{code}", "失败");
                }
            ));

        }

        /// <summary>
        /// 获取更新用户的信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btGetUserInfo_Click(object sender, EventArgs e)
        {
            //将当前用户名也添加进List
            var UserName = txtUpdateUserId.Text.Trim();
            List<string> UserList = new List<string>();
            UserList.Add(UserName);

            //获取UserInfo
            SDKClient.Instance.UserInfoManager.FetchUserInfoByUserId(UserList, new ValueCallBack<Dictionary<string, UserInfo>>(
               onSuccess: (listUserInfo) =>
               {
                   foreach (var item in listUserInfo)
                   {
                       txtInfo.Text += "工号：" + item.Key.ToString() + "\r\n";
                       txtInfo.Text += "用户名：" + item.Value.NickName + "\r\n";
                       txtInfo.Text += "=====================" + "\r\n";
                   }
                  
               }, onError: (code, desc) =>
               {
                   MessageBoxEx.Show($"获取用户信息失败,code:{code}, desc:{code}", "失败");
               }));
        }
    }
}
